package com.jrx.anytxn.reporting.job.reportingFile.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.ReportingFileConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @author liuyu
 * @Description 合并报送文件监听，当文件存在时删除
 */
@Service
public class MergeReportingFileListener implements JobExecutionListener {
	@Autowired
	private ReportingFileConfig reportingFileConfig;
	@Autowired
	private IOrganizationTableService organizationTableService;

	@Override
	public void beforeJob(JobExecution jobExecution) {
		String filePath = reportingFileConfig.getReportingFilePath();
		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
		Date businessDate = org.getToday();
		String toDay = DateUtils.format(businessDate, "yyyyMMdd");
		String reportingPath = filePath + org.getTenantId() + File.separator + toDay + File.separator;

		Path path = Paths.get(reportingPath);
		File toFile = path.toFile();
		if (Files.exists(path) && Files.isDirectory(path)) {
			File[] files = toFile.listFiles();
			if (files.length > 0) {
				for (File file : files) {
					String fileName = file.getName();
					// 合并文件、.ok文件删除
					if (fileName.endsWith("_" + toDay + ".txt") || fileName.endsWith(toDay + ".ok")) {
						file.delete();
					}

				}
			}

		}
	}

	@Override
	public void afterJob(JobExecution jobExecution) {

	}
}
